package com.portal.cwegportal.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.portal.cwegportal.model.socket.Message;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

//@ServerEndpoint(value = "/websocket/username")
//@ServerEndpoint(value = "/websocket/username",configurator = SpringConfigurator.class)

@Component
@ServerEndpoint("/websocket/{usercode}/{username}")
public class WebSocket {

    private static int onlineCount = 0;
    private static int onlineUserCount = 0;
    private static Map<String, WebSocket> clients = new IdentityHashMap<String, WebSocket>();

    private Session session;
    private String username;


    @OnOpen
    public void onOpen(@PathParam("usercode") String userCode,@PathParam("username") String userName,Session session) throws IOException {

        //@PathParam("username") String username,
        //String username="kitty";
        this.username = userName+"-"+userCode;
        this.session = session;
        addOnlineCount();
        clients.put(username, this);
        String[] keys= Arrays.stream(WebSocket.clients.keySet().stream().distinct().toArray(size -> new String[size])).distinct().toArray(size -> new String[size]);
        broadcastOnlineUser(keys.length);
        System.out.println("已连接");
    }


    @OnClose
    public void onClose() throws IOException {
        clients.remove(this.username,this); String[] keys= Arrays.stream(WebSocket.clients.keySet().stream().distinct().toArray(size -> new String[size])).distinct().toArray(size -> new String[size]);
        broadcastOnlineUser(keys.length);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        //JSONObject jsonTo = JSONObject.parseObject(message);
        Message msg= JSON.parseObject(message,Message.class);
        msg.setType("msg");
        msg.setFrom(this.username);
        String jsonMsg=JSON.toJSONString(msg);
        sendMessageTo(jsonMsg, msg.getTo());

//        if (!jsonTo.get("To").equals("All")){
//            sendMessageTo("给一个人", jsonTo.get("To").toString());
//        }else{
//            sendMessageAll("给所有人");
//        }
    }
    @OnError
    public void onError(Session session, Throwable error) throws  Exception{
        BusinessLogger.Info(LoggerGenre.View,"websocket 发生错误",error);
        error.printStackTrace();
    }

    public void sendMessageTo(String message, String To) throws IOException {
        // session.getBasicRemote().sendText(message);
        //session.getAsyncRemote().sendText(message);

        for (WebSocket item : clients.values()) {
            if (item.username.equals(To) )
                item.session.getAsyncRemote().sendText(message);
        }
    }
    public void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }
    public void broadcastOnlineUser (int onlineUserCount)throws IOException {
        Message message=new Message();
        message.setType("onlineUser");
        String[] keys= Arrays.stream(WebSocket.clients.keySet().stream().distinct().toArray(size -> new String[size])).distinct().toArray(size -> new String[size]);

        message.setOnlineUsers(keys);
        message.setOnlineUserCount(onlineUserCount);
        String jsonMessage=JSONObject.toJSONString(message);

        sendMessageAll(jsonMessage);
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }



    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }
}
